package com.lanzuo.collector.updater.service;

import com.lanzuo.collector.updater.config.SpringContextHolder;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.RemoteResourceInfo;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author eric
 * 远程获取文件夹下文件
 */
public class RemoteFileLister {
    private final Integer port;
    private final String user;
    private final String password;
    private final String remoteDir;
    private final String ip;
    private SSHClient ssh;

    public RemoteFileLister() {
        ip = SpringContextHolder.getProperty("file_server.ip");
        port = SpringContextHolder.getProperty("file_server.port", Integer.class, 22);
        user = SpringContextHolder.getProperty("file_server.user");
        password = SpringContextHolder.getProperty("file_server.password");
        remoteDir = SpringContextHolder.getProperty("file_server.dir_path");

        ssh = initSshClient();
    }

    /**
     * 获取远程目录中最新的普通文件（按修改时间）
     *
     * @return 最新的文件信息，若无文件则返回 empty
     * @throws Exception SFTP 操作异常
     */
    public Optional<RemoteResourceInfo> getLatestFile() {
        if (!ssh.isConnected()) {
            ssh = initSshClient();
        }

        try (SFTPClient sftp = ssh.newSFTPClient()) {
            return sftp.ls(remoteDir).stream()
                    .filter(RemoteResourceInfo::isRegularFile)
                    .max(Comparator.comparingLong(f -> f.getAttributes().getMtime()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 初始化ssh client
     *
     * @return
     */
    private SSHClient initSshClient() {
        SSHClient ssh = new SSHClient();
        try {
            ssh.addHostKeyVerifier(new PromiscuousVerifier()); // 生产环境应使用严格验证
            ssh.connect(ip, port);
            ssh.authPassword(user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ssh;
    }

    /**
     * 根据正则表达式获取匹配的文件列表
     * d
     *
     * @param fileRegex 文件名正则表达式，如 ".*\\.log$" 或 "report_\\d{8}\\.csv"
     * @return 匹配的文件列表（仅普通文件）
     * @throws Exception SFTP 操作异常
     */
    public List<RemoteResourceInfo> getFilesByRegex(String fileRegex) {
        if (!ssh.isConnected()) {
            ssh = initSshClient();
        }

        Pattern pattern = Pattern.compile(fileRegex);
        try (SFTPClient sftp = ssh.newSFTPClient()) {
            return sftp.ls(remoteDir).stream()
                    .filter(RemoteResourceInfo::isRegularFile)
                    .filter(file -> pattern.matcher(file.getName()).matches())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 列出远程文件
     *
     * @return 文件列表
     */
    public List<String> listRemoteFiles() {
        if (!ssh.isConnected()) {
            ssh = initSshClient();
        }

        try (SFTPClient sftp = ssh.newSFTPClient()) {
            return sftp.ls(remoteDir).stream()
                    .filter(RemoteResourceInfo::isRegularFile) // 只列文件
                    .map(RemoteResourceInfo::getName)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}